<template>
  <div class="page-home-index" v-loading="!isLoad">
    <div class="search-bar">
      <el-radio-group v-model="type" @change="changeType">
        <el-radio-button v-for="(item,index) in initData.types" :key="index" :label="item.id">{{item.name}}</el-radio-button>
      </el-radio-group>
      <el-form size="small" :model="searchAir" label-width="0px" class="m-t-10" v-if="type == 'Air'">
        <el-form-item class="select-date">
          <div class="flex-block">
          <el-radio-group v-model="searchAir.timeType" @change="changeTimeTypeAir">
            <el-radio-button v-for="(item,index) in initDataAir.timeTypes" :key="index" :label="item.id">{{ item.name }}</el-radio-button>
          </el-radio-group>
          <div class="flex-block btn-control m-l-10" style="flex:1">
          <el-button class="btn-left" icon="el-icon-arrow-left" :disabled="btnDisabledAir.prev" @click="handleDateAir('prev')"></el-button>
          <el-date-picker
            v-show="searchAir.timeType == 'hour'"
            v-model="searchAir.dateTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            @change="getListAir"
            popper-class="drawer-date-range"
            :picker-options="pickerDateAir">
          </el-date-picker>
          <el-date-picker
            v-show="searchAir.timeType == 'day'"
            v-model="searchAir.date"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            @change="getListAir"
            :picker-options="pickerDateAirTime">
          </el-date-picker>
          <el-button class="btn-right" icon="el-icon-arrow-right" :disabled="btnDisabledAir.next" @click="handleDateAir('next')"></el-button>
          <el-button class="btn-play" :icon="intervalAir.t ? 'el-icon-video-pause' : 'el-icon-video-play'" circle @click="autoPlayAir"></el-button>
        </div>
        </div>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="searchAir.renderer" @change="changeTypeAir" >
            <template v-if="searchAir.timeType == 'hour'">
              <el-radio-button v-for="(item,index) in initDataAir.timeRender" :key="index" :label="item.id">{{ item.name }}</el-radio-button>
            </template>
            <template v-else>
              <el-radio-button v-for="(item,index) in initDataAir.dateRender" :key="index" :label="item.id">{{ item.name }}</el-radio-button>
            </template>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form size="small" :model="searchLive" label-width="0px" class="m-t-10 form-live-weather" v-if="type == 'Live'">
        <el-form-item class="select-date">
          <div class="flex-block btn-control">
          <el-button class="btn-left" icon="el-icon-arrow-left" @click="handleDateLive('prev')"></el-button>
          <el-date-picker
            v-model="searchLive.dt"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
            popper-class="drawer-date-range"
            :default-time="defaultTimeLive"
            @change="getListLive"
            :picker-options="pickerDateLive">
          </el-date-picker>
          <el-button class="btn-right" icon="el-icon-arrow-right" :disabled="btnDisabledLive.next" @click="handleDateLive('next')"></el-button>
        </div>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="searchLive.type" @change="changeTypeLive">
            <el-radio-button v-for="(item,index) in initDataLive.types" :key="index" :label="item.value">{{ item.label }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form size="small" :model="searchPoll" label-width="0px" class="m-t-10 form-pollutant-source" v-if="type == 'Poll'">
          <el-form-item>
            <el-radio-group v-model="searchPoll.areas" @change="changeAreas">
              <el-radio-button v-for="(item,index) in initDataPoll.areas" :key="index" :label="item.value">{{item.label}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="searchPoll.areas > 0">
            <el-select v-model="initDataPoll.stationsChecked" placeholder="请选择" @change="changeStations" multiple>
              <el-option v-for="(item,index) in initDataPoll.stations" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchPoll.county" placeholder="请选择" @change="handleFilter" :disabled="userInfo.is_region_user">
              <el-option v-for="(item,index) in initDataPoll.countys" :key="index" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="form-class">
            <el-select v-model="searchPoll.class" placeholder="请选择" @change="changeClass" multiple>
              <el-option v-for="(item,index) in initDataPoll.classes" :key="index" :label="item.label" :value="item.label"></el-option>
            </el-select>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item class="form-industries" v-if="searchPoll.class.indexOf('工业源') != -1">
            <el-checkbox :indeterminate="indeterminateIndustries" v-model="checkedAllIndustries" @change="changeCheckAllIndustries">全选</el-checkbox>
            <el-select
              v-model="searchPoll.industries"
              multiple
              collapse-tags
              class="select-industries"
              placeholder="请选择"
              @change="changeIndustries">
              <el-option
                v-for="item in initDataPoll.industries"
                :key="item.id"
                :label="item.text"
                :value="item.text">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input placeholder="输入污染源名称" v-model="searchPoll.searchText" clearable class="btn-search">
              <el-button slot="append" icon="el-icon-search" size="small" type="primary" @click="handleFilter"></el-button>
            </el-input>
          </el-form-item>
        </el-form>
    </div>
    <div class="map" id="coordinates" ref="basicMapbox" :style="{height:domHeight + 'px',width:'100%'}"></div>
  </div>
</template>
<script>
// import * as mapboxgl from 'mapbox-gl';
import {city, cityPinyin,cityMapCenter, geoserver} from '@/config/env';
import air from './components/air';
import live from './components/live';
import poll from './components/poll';
export default {
  mixins: [air, live, poll],
  data() {
    return {
      map: null,
      marker: null,
      mapboxToken: 'pk.eyJ1Ijoic25zcXNzIiwiYSI6ImNrZ2oxbWtqMTAzNnAyeXFwMDAzdmp2YTAifQ.AuaHmI9j-_VbOYxUSJACQw',
      meteoblueMaps: null,
      externals: [],
      domHeight: 0,
      isLoad: false,
      list:[],
      type: 'Air',
      initData:{
        types:[
          {id: 'Air', name: '空气质量'},
          {id: 'Live', name: '实况气象'},
          {id: 'Poll', name: '污染排放'},
        ]
      },
      layers:[
        'air-monitor',
        'live-weather-layer', 
        'live-weather-label', 
        'live-weather-source',
        'station-layer',
        'circle',
        'station_emis_circle',
        'stations_inventory_' + cityPinyin,
        'stations_inventory_circle_'+cityPinyin
      ],
    }
  },
  async created() {
    this.domHeight = document.body.clientHeight - 60 - 40 - 4;
    await this.loadCss();
    await this.loadScript(
      'https://static.meteoblue.com/cdn/mapbox-gl-js/v1.11.1/mapbox-gl.js',
      'sha512-v5PfWsWi47/AZBVL7WMNqdbM1OMggp9Ce408yX/X9wg87Kjzb1xqpO2Ul0Oue8Vl9kKOcwPM2MWWkTbUjRxZOg=='
    );
    await this.loadScript(
      'https://static.meteoblue.com/lib/maps-plugin/v0.x/maps-plugin.js'
    );
    this.createMap();
  },
  methods: {
    createMap() {
      const map = new mapboxgl.Map({
        container: this.$refs.basicMapbox,
        accessToken: this.mapboxToken,
        center: cityMapCenter,
        zoom: 8.5,
        hash: false,
        attributionControl: false,
        keyboard: false,   
      });
      const lang = 'zh';
      const apiKey = '1iw4Jq5NZK60Ig7O';//'ZEa5n8pTuPwFf0dH'; //
      const maps = 'windAnimation,wind,temperature,obsTemperature,humidity,pressure,totalClouds,highClouds,midClouds,lowClouds,precipitationDaily,obsPrecipitation,solarIradiation,sunshine,temperatureTendency,ozone,particulateMatter,no2,gph500,boundaryLayerHeight,aerosolOpticalDepth,uvIndex,windSpeedAnomaly,temperatureAnomaly,precipAnomaly,gph850temperature,temperatureAnomaly850';
      const overlay = 'domainBoundary,graticuleOverlay,pressure2mOverlay,temperatureObsOverlay';
      const temperatureUnit = 'C';
      const velocityUnit = 'm/s';


      // The URL to the Inventory JSON. In this case the meteoblue API will generate one with some specified maps.
      const inventoryUrl = `https://maps-api.meteoblue.com/v1/map/inventory/filter?maps=${maps}&overlays=${overlay}&lang=${lang}&apikey=${apiKey}&temperatureUnit=${temperatureUnit}&velocityUnit=${velocityUnit}`;

      // Initialize the meteoblue Maps Plugin. It will generate a user interface on top of the Mapbox GL JS map according to the inventory JSON.
      const meteoblueMaps = new meteoblueMapsPlugin({
        mapboxMap: map,
        inventory: inventoryUrl,
        apiKey: apiKey,
        showSidebar: true,
        timezoneOffsetInSeconds: 28800,
        timezoneAbbreviation: '北京时',
        canUseRestricted: true,
      });
      this.meteoblueMaps = meteoblueMaps;
      map.on('load', () => {
        this.map = map;
        this.isLoad = true;      
      });
      map.on('idle', (evt) => {
        this.addBorder();
        console.log(this.map.getStyle().layers);
      });
      this.meteoblueMaps.on('menuchange', () => {
        this.changeType();        
      });
    },
    
    addBorder() {
      if (!this.map) {
        return;
      }
      if (!this.map.getLayer('area-border')) {
        this.map.addLayer({
          id: 'area-border',
          type: 'line',
          'source': {
            'scheme':'tms',
            'type': 'vector',
            'tiles': [
                geoserver + '/gwc/service/tms/1.0.0/air:region@EPSG:900913@pbf/{z}/{x}/{y}.pbf'
            ]
          },
          'source-layer': 'region',
          filter: ['all', ['==', 'name', city], ['==', 'level', 2]],
          minzoom: 1,
          maxzoom: 19,
          paint: {
            'line-color': '#ff9800',
            'line-width': 2
          }
        });
      }
    },

    async loadScript(src, integrity) {
      const head = document.getElementsByTagName('head')[0];
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = src;
      // if (integrity) {
      //   script.integrity = integrity;
      // }
      script.crossorigin = 'anonymous';
      head.append(script);
      this.externals.push(script);
      return new Promise((resolve, reject) => {
        script.onload = () => {
          resolve('success');
        };
        script.onerror = () => {
          reject('error');
        };
      });
    },

    async loadCss() {
      const head = document.getElementsByTagName('head')[0];
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.crossorigin = 'anonymous';
      // link.integrity = 'sha512-xY1TAM00L9X8Su9zNuJ8nBZsGQ8IklX703iq4gWnsw6xCg+McrHXEwbBkNaWFHSqmf6e7BpxD6aJQLKAcsGSdA==';
      link.href = 'https://static.meteoblue.com/cdn/mapbox-gl-js/v1.11.1/mapbox-gl.css';
      head.append(link);
      return new Promise((resolve, reject) => {
        link.onload = () => {
          resolve('success');
        };
        link.onerror = () => {
          reject('error');
        };
      });
    },
    changeType(){      
      clearInterval(this.intervalAir.t);
      this.intervalAir.t = null;
      this.removeLayer();
      this['getList'+this.type]();
    },
    removeLayer(){
      console.log('removeLayer')
        this.layers.forEach(item => {
          if (this.map.getLayer(item)) this.map.removeLayer(item);
          if (this.map.getSource(item)) this.map.removeSource(item); 
        });
    },
  }
}
</script>